import { IRootReducerState } from '@/store/root-reducer';
import { parentToTree } from '@/utils/converter';
import { Input, Tree } from '@douyinfe/semi-ui';
import { useEffect, useMemo } from 'react';
import { useSelector, shallowEqual } from 'react-redux';
import * as action from '@/redux/role/role-actions';
import { useDispatch } from 'react-redux';
import { TreeNodeData } from '@douyinfe/semi-ui/lib/es/tree';

const AppMenuTree = ({
  appId,
  allSelect,
  collapse,
  onSelectItem,
}: {
  appId: any;
  allSelect: boolean;
  collapse: boolean;
  onSelectItem?: (
    selectedKeys: string,
    selected: boolean,
    selectedNode: TreeNodeData
  ) => void;
}) => {
  const dispatch = useDispatch<any>();
  const { role } = useSelector<IRootReducerState, any>(
    (state) => ({ role: state.role }),
    shallowEqual
  );
  const { appMenuEntities } = role;
  const treeData = [
    {
      label: 'Asia',
      value: 'Asia',
      key: '0',
      children: [
        {
          label: 'China',
          value: 'China',
          key: '0-0',
          children: [
            {
              label: 'Beijing',
              value: 'Beijing',
              key: '0-0-0',
            },
            {
              label: 'Shanghai',
              value: 'Shanghai',
              key: '0-0-1',
            },
          ],
        },
        {
          label: 'Japan',
          value: 'Japan',
          key: '0-1',
          children: [
            {
              label: 'Osaka',
              value: 'Osaka',
              key: '0-1-0',
            },
          ],
        },
      ],
    },
    {
      label: 'North America',
      value: 'North America',
      key: '1',
      children: [
        {
          label: 'United States',
          value: 'United States',
          key: '1-0',
        },
        {
          label: 'Canada',
          value: 'Canada',
          key: '1-1',
        },
      ],
    },
  ];

  useEffect(() => {
    if (!appId) return;
    dispatch(action.fetchAppMenuItems(appId));
  }, [appId]);

  const treeitems = useMemo(
    () =>
      parentToTree(
        appMenuEntities,
        Math.min(...appMenuEntities.map((e: any) => e.parentId)),
        'name'
      ),
    [appMenuEntities]
  );
  console.log('获取权限树--->', appMenuEntities, treeitems);
  return (
    <Tree
      treeData={treeitems}
      multiple
      expandAll={collapse}
      onSelect={onSelectItem}
    />
  );
};

export default AppMenuTree;
